package com.example.smartwaterapi.service.impl;

import com.example.smartwaterapi.service.WeatherService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 天气服务实现类 - 使用Open-Meteo API
 */
@Slf4j
@Service
public class WeatherServiceImpl implements WeatherService {

    @Value("${weather.api.base-url:https://api.open-meteo.com/v1}")
    private String weatherApiBaseUrl;
    
    @Autowired
    private RestTemplate restTemplate;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取当前天气
     */
    @Override
    public Map<String, Object> getCurrentWeather() {
        // 默认获取北京天气（应由前端传入实际坐标）
        return getWeatherByLocation(39.9042, 116.4074);
    }
    
    /**
     * 根据经纬度获取天气 - 使用Open-Meteo API
     */
    @Override
    public Map<String, Object> getWeatherByLocation(Double latitude, Double longitude) {
        log.info("获取位置天气: 纬度={}, 经度={}", latitude, longitude);
        
        if (latitude == null || longitude == null) {
            log.error("经纬度参数不能为空");
            return createErrorResponse("经纬度参数不能为空");
        }
        
        try {
            // 调用Open-Meteo API获取天气数据
            String url = String.format(
                "%s/forecast?latitude=%.6f&longitude=%.6f&current=true",
                weatherApiBaseUrl, latitude, longitude
            );
            
            log.info("请求Open-Meteo API: {}", url);
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                // 解析响应
                JsonNode rootNode = objectMapper.readTree(response.getBody());
                JsonNode currentWeather = rootNode.path("current");
                
                if (!currentWeather.isMissingNode()) {
                    // 构建结果
                    Map<String, Object> result = new HashMap<>();
                    double temperature = currentWeather.path("temperature_2m").asDouble();
                    double windSpeed = currentWeather.path("wind_speed_10m").asDouble();
                    int windDirection = currentWeather.path("wind_direction_10m").asInt();
                    
                    result.put("temperature", (int)temperature); // 四舍五入为整数
                    result.put("condition", getWeatherConditionByTemperature(temperature)); // 简单根据温度推断天气
                    result.put("wind", getWindDescription(windSpeed, windDirection));
                    result.put("updateTime", LocalDateTime.now().toString());
                    result.put("source", "Open-Meteo API");
                    
                    log.info("Open-Meteo天气数据处理成功: {}", result);
                    return result;
                } else {
                    log.error("API返回数据格式错误，无current_weather字段");
                    return createErrorResponse("API返回数据格式错误");
                }
            } else {
                log.error("API返回异常状态码: {}", response.getStatusCode());
                return createErrorResponse("API返回异常状态码: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("获取天气异常: {}", e.getMessage(), e);
            return createErrorResponse("获取天气异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据城市获取天气 - 转为调用getWeatherByLocation方法
     */
    @Override
    public Map<String, Object> getWeatherByCity(String city) {
        log.info("获取城市天气: {}", city);
        
        // 根据城市名获取经纬度 - 在实际应用中可能需要调用地理编码API
        double[] coordinates = getCoordinatesByCity(city);
        
        // 使用经纬度获取天气
        return getWeatherByLocation(coordinates[0], coordinates[1]);
    }
    
    /**
     * 根据城市名称获取经纬度坐标
     */
    private double[] getCoordinatesByCity(String city) {
        // 这里可以实现一个完整的城市到坐标的映射
        switch (city) {
            case "北京":
                return new double[]{39.9042, 116.4074};
            case "上海":
                return new double[]{31.2304, 121.4737};
            case "广州":
                return new double[]{23.1291, 113.2644};
            case "深圳":
                return new double[]{22.5431, 114.0579};
            case "杭州":
                return new double[]{30.2741, 120.1551};
            case "南京":
                return new double[]{32.0617, 118.7778};
            case "成都":
                return new double[]{30.5728, 104.0668};
            case "重庆":
                return new double[]{29.5630, 106.5530};
            case "武汉":
                return new double[]{30.5928, 114.3055};
            case "西安":
                return new double[]{34.3416, 108.9398};
            default:
                // 默认返回北京坐标
                return new double[]{39.9042, 116.4074};
        }
    }
    
    /**
     * 根据风速和风向获取风向描述
     */
    private String getWindDescription(double windSpeed, int windDirection) {
        // 风向
        String direction;
        if (windDirection >= 337.5 || windDirection < 22.5) {
            direction = "北风";
        } else if (windDirection >= 22.5 && windDirection < 67.5) {
            direction = "东北风";
        } else if (windDirection >= 67.5 && windDirection < 112.5) {
            direction = "东风";
        } else if (windDirection >= 112.5 && windDirection < 157.5) {
            direction = "东南风";
        } else if (windDirection >= 157.5 && windDirection < 202.5) {
            direction = "南风";
        } else if (windDirection >= 202.5 && windDirection < 247.5) {
            direction = "西南风";
        } else if (windDirection >= 247.5 && windDirection < 292.5) {
            direction = "西风";
        } else {
            direction = "西北风";
        }
        
        // 风力等级
        String level;
        if (windSpeed < 1) {
            level = "无风";
        } else if (windSpeed < 6) {
            level = "1-2级";
        } else if (windSpeed < 12) {
            level = "3-4级";
        } else if (windSpeed < 20) {
            level = "5-6级";
        } else if (windSpeed < 28) {
            level = "7-8级";
        } else if (windSpeed < 37) {
            level = "9-10级";
        } else {
            level = "11级以上";
        }
        
        return direction + " " + level;
    }
    
    /**
     * 根据温度简单推断天气状况
     * 注意：这只是一个简单的推断，实际天气状况应该通过API获取
     */
    private String getWeatherConditionByTemperature(double temperature) {
        // 简单根据温度判断天气状况
        if (temperature > 30) {
            return "晴";
        } else if (temperature > 20) {
            return "多云";
        } else if (temperature > 10) {
            return "阴";
        } else if (temperature > 0) {
            return "小雨";
        } else {
            return "小雪";
        }
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String errorMessage) {
        Map<String, Object> response = new HashMap<>();
        response.put("error", errorMessage);
        response.put("temperature", 0);
        response.put("condition", "未知");
        response.put("wind", "未知");
        response.put("updateTime", LocalDateTime.now().toString());
        response.put("source", "错误响应");
        return response;
    }
}
